<?php
/**
 * GeoContexter
 * @link http://code.google.com/p/geocontexter/
 * @package GeoContexter
 */

/**
 * Update record
 *
   USAGE:
   <pre>

   $RecordImageUpdate = $this->CoreModel('RecordUpdate');

   $params  = array('id_image' => bigint,
                    'data'     => array('title'       => string,
                                        'description' => string));

   $result  = $RecordImageUpdate->run( $params );

   if ($result instanceof \Core\Library\Exception) {
       return $this->error( $result->getMessage(), __file__, __line__);
   }

   </pre>
 * @package GeoContexter
 * @subpackage Module_Geocontexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev: 768 $ / $LastChangedDate: 2010-12-16 16:11:56 +0100 (jeu., 16 dÃ©c. 2010) $ / $LastChangedBy: armand.turpel $
 */

namespace Geocontexter\Model;

use Core\Model\AbstractModel;
use Core\Model\InterfaceModel;

class RecordUpdate extends    AbstractModel
                   implements InterfaceModel
{
    /**
     * allowed fields
     *
     *
     * @param array $allowed_fields
     */

    private $allowed_fields = array('id_item'            => true,
                                    'id_modifier'        => true,
                                    'id_project'         => true,
                                    'id_attribute_group' => true,
                                    'id_status'          => true,
                                    'date_record_start'  => true,
                                    'date_record_end'    => true,
                                    'timezone'           => true,
                                    'attribute_value'    => true,
                                    'media_folder_hash'  => true,);

    /**
     *
     *
     * @param array $params
     */
    public function run( $params )
    {
        try {

            $this->beginTransaction();

            $this->validate_params($params);

            //$params['data']['update_time'] = new \Zend\Db\Sql\Expression("CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC'");

            $current_media_folder_hash = $this->get_media_folder_hash( $params['id_record'] );
            $new_media_folder_hash     = $params['data']['media_folder_hash'];

            if (!empty( $new_media_folder_hash ) && !empty( $current_media_folder_hash )) {

              unset($params['data']['media_folder_hash']);
              $_media_folder_hash = $current_media_folder_hash;

            } else {
              $_media_folder_hash = $new_media_folder_hash;
            }

            if (isset($params['data']['attribute_value'])) {
              $params['data']['attribute_value'] = new \Zend\Db\Sql\Expression($params['data']['attribute_value']);
            }

            $this->update('gc_record','geocontexter', $params['data'], array('id_record' => $params['id_record']));

      // update geometry

            if (isset($params['geom_point'])) {

                $_tmp_geom_point = $params['geom_point'];//new \Zend\Db\Sql\Expression($params['geom_point']);

                $this->query("UPDATE geocontexter.gc_record_geometry
                               SET geom_point = {$_tmp_geom_point}
                               WHERE id_record = {$params['id_record']}");

            } elseif(isset($params['geom_linestring'])) {

                $_tmp_geom_linestring = new \Zend\Db\Sql\Expression($params['geom_linestring']);

                $this->query("UPDATE geocontexter.gc_record_geometry
                               (id_record,geom_linestring)
                               VALUES ({$params['id_record']}, {$_tmp_geom_linestring})");

            } elseif(isset($params['geom_polygon'])) {

                $_tmp_geom_polygon = new \Zend\Db\Sql\Expression($params['geom_polygon']);

                $this->query("UPDATE geocontexter.gc_record_geometry
                               (id_record,geom_polygon)
                               VALUES ({$params['id_record']}, {$_tmp_geom_polygon})");

            }

            $this->commit();

            return array('media_folder_hash'  => $_media_folder_hash);

        } catch(\Exception $e) {
            $this->rollback();
            throw $e;
        }
    }

    /**
     * set and validate parameters
     *
     *
     * @param array $params
     */
    private function get_media_folder_hash( $id_record )
    {
        $sql = 'SELECT media_folder_hash FROM geocontexter.gc_record WHERE id_record = ?';

        $result = $this->query($sql, array($id_record));

        if (isset($result[0]['media_folder_hash'])) {
            return $result[0]['media_folder_hash'];
        } else {
            return '';
        }
    }

    /**
     * set and validate parameters
     *
     *
     * @param array $params
     */
    private function validate_params( & $params )
    {
        if (!isset($params['data'])) {
            throw new \Exception('data array isnt defined');
        }

        foreach ($params['data'] as $key => $val) {
            if (!isset($this->allowed_fields[$key])) {
                throw new \Exception('Field isnt allowed: ' . $key);
            }
        }

        if (!isset($params['id_record'])) {
            throw new \Exception('id_record field isnt defined');
        }

        $val_digits = new \Zend\Validator\Digits();

        if (false === $val_digits->isValid($params['id_record']))  {
            throw new \Exception('id_record isnt from type bigint');
        }
    }
}
